package com.cn.sql.handler;

import com.cn.sql.annotation.SqlFormat;
import org.apache.ibatis.cache.CacheKey;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.executor.statement.StatementHandler;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.ParameterMapping;
import org.apache.ibatis.mapping.SqlSource;
import org.apache.ibatis.plugin.Interceptor;
import org.apache.ibatis.plugin.Intercepts;
import org.apache.ibatis.plugin.Invocation;
import org.apache.ibatis.plugin.Signature;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;

import java.lang.reflect.Method;
import java.sql.Connection;
import java.util.Objects;
import java.util.Properties;

/**
 * 类简介: SQL 侦听器
 *
 * @Author: ShangGuan
 * @Time: 2024/06/06
 **/
@Intercepts(
        {
                @Signature(type = StatementHandler.class, method = "prepare", args = {Connection.class, Integer.class}),
                @Signature(type = Executor.class, method = "update", args = {MappedStatement.class, Object.class}),
                @Signature(type = Executor.class, method = "query", args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class}),
                @Signature(type = Executor.class, method = "query", args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class, CacheKey.class, BoundSql.class}),
        }
)
public abstract class SqlInterceptor implements Interceptor {


    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        try {
            Object[] args = invocation.getArgs();
            if (args[0] instanceof MappedStatement) {
                MappedStatement ms = (MappedStatement) args[0];
                SqlFormat sqlFormat = getSqlFormat(ms);
                BoundSql boundSql = ms.getBoundSql(args[1]);
                String oldSql = boundSql.getSql();
                if (Objects.isNull(sqlFormat)) {
                    return invocation.proceed();
                }
                // 生成新的 SQL
                String newSql = generationSql(ms, oldSql, args[1]);
                // 重新塞回去
                BoundSql newBoundSql = new BoundSql(ms.getConfiguration(), newSql, boundSql.getParameterMappings(), boundSql.getParameterObject());
                for (ParameterMapping mapping : boundSql.getParameterMappings()) {
                    String prop = mapping.getProperty();
                    if (boundSql.hasAdditionalParameter(prop)) {
                        newBoundSql.setAdditionalParameter(prop, boundSql.getAdditionalParameter(prop));
                    }
                }
                MappedStatement newMs = newMappedStatement(ms, newBoundSql);
                args[0] = newMs;
                args[5] = newBoundSql;
                return invocation.proceed();
            }
        } catch (Exception exception) {
            throw new RuntimeException("mybatis handler is exception");
        }
        return invocation.proceed();
    }


    /**
     * 生成新的SQL
     *
     * @param oldSql      旧 SQL
     * @param paramObject param 对象
     * @return {@link String }
     **/
    protected abstract String generationSql(MappedStatement ms, String oldSql, Object paramObject);


    private SqlFormat getSqlFormat(MappedStatement mappedStatement) {
        String id = mappedStatement.getId();
        // 获取 Class Method
        String clazzName = id.substring(0, id.lastIndexOf('.'));
        String mapperMethod = id.substring(id.lastIndexOf('.') + 1);

        Class<?> clazz;
        try {
            clazz = Class.forName(clazzName);
        } catch (ClassNotFoundException e) {
            return null;
        }
        SqlFormat sqlFormat = clazz.getAnnotation(SqlFormat.class);
        if (sqlFormat != null) {
            return sqlFormat;
        }
        Method[] methods = clazz.getMethods();
        for (Method method : methods) {
            if (method.getName().equals(mapperMethod)) {
                sqlFormat = method.getAnnotation(SqlFormat.class);
                break;
            }
        }
        return sqlFormat;
    }

    /**
     * 构建新的MappedStatement
     *
     * @param ms          MappedStatement
     * @param newBoundSql 新绑定 SQL
     * @return {@link MappedStatement }
     **/
    private MappedStatement newMappedStatement(MappedStatement ms, BoundSql newBoundSql) {
        MappedStatement.Builder builder = new
                MappedStatement.Builder(ms.getConfiguration(), ms.getId(), new BoundSqlSource(newBoundSql), ms.getSqlCommandType());
        builder.resource(ms.getResource());
        builder.fetchSize(ms.getFetchSize());
        builder.statementType(ms.getStatementType());
        builder.keyGenerator(ms.getKeyGenerator());
        if (ms.getKeyProperties() != null && ms.getKeyProperties().length > 0) {
            builder.keyProperty(ms.getKeyProperties()[0]);
        }
        builder.timeout(ms.getTimeout());
        builder.parameterMap(ms.getParameterMap());
        builder.resultMaps(ms.getResultMaps());
        builder.resultSetType(ms.getResultSetType());
        builder.cache(ms.getCache());
        builder.flushCacheRequired(ms.isFlushCacheRequired());
        builder.useCache(ms.isUseCache());

        return builder.build();
    }

    @Override
    public Object plugin(Object target) {
        return Interceptor.super.plugin(target);
    }

    @Override
    public void setProperties(Properties properties) {
        Interceptor.super.setProperties(properties);
    }

    static class BoundSqlSource implements SqlSource {
        private BoundSql boundSql;

        public BoundSqlSource(BoundSql boundSql) {
            this.boundSql = boundSql;
        }

        public BoundSql getBoundSql(Object parameterObject) {
            return boundSql;
        }
    }
}